import axios from 'axios'
import { BasicUtils } from './basic.utils'

const request = axios.create({
  timeout: 3000,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  }
})

request.interceptors.request.use(
  (config) => {
    console.log('请求参数: 🚀 ~', config.data ?? config.params)
    console.log('请求方式: 🚀 ~', config.method)
    const url = config.url
    const token = BasicUtils.getStorage('token')
    if (token) {
      config.headers['Authori-Zation'] = `${token}`
    }
    config.url = `${process.env.TARO_APP_BASE_URL}api/${url}`
    return Promise.resolve(config)
  },
  (err) => {
    return Promise.reject(err)
  }
)

request.interceptors.response.use(
  (response) => {
    console.log('返回参数: 🚀 ~', response.data)
    switch (response.data.code) {
      case 200:
        return Promise.resolve(response.data)
      case 401:
        console.log(response.data.message)
        return Promise.reject(response.data)
      default:
        return Promise.reject(response.data)
    }
  },
  (err) => {
    console.error('响应错误: 🚀 ~', err)
    switch (err.state) {
      case 400:
        return Promise.reject(err.data)
      case 301:
        return Promise.reject(err.data)
    }
  }
)

export default request
